package com.example.demo.zookeeper.mytest.config;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @author liweizhi
 * @date 2020/6/23
 */
public class WatcherCallback implements Watcher, AsyncCallback.StatCallback, AsyncCallback.DataCallback {

    private ZooKeeper zk;
    private MyConf conf;
    private CountDownLatch cdl = new CountDownLatch(1);

    public ZooKeeper getZk() {
        return zk;
    }

    public void setZk(ZooKeeper zk) {
        this.zk = zk;
    }

    public MyConf getConf() {
        return conf;
    }

    public void setConf(MyConf conf) {
        this.conf = conf;
    }

    public void aWait() {
        zk.exists(ZkUtil.configPath, this, this, "qwe");
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("watcherCallback: " + event.toString());
        switch (event.getType()) {
            case None:
                break;
            case NodeCreated:
                // 创建了,要getData,以更新Config
                zk.getData(ZkUtil.configPath, this, this, "qwe");
                break;
            case NodeDeleted:
                // 删除了,要重新等着它被创建
                conf.setConf("");
                cdl = new CountDownLatch(1);
                break;
            case NodeDataChanged:
                // 更新了,要getData,以更新Config
                zk.getData(ZkUtil.configPath, this, this, "qwe");
                break;
            case NodeChildrenChanged:
                // 子节点更新,这里不关注子节点
                break;
            case DataWatchRemoved:
                break;
            case ChildWatchRemoved:
                break;
            case PersistentWatchRemoved:
                break;
            default:
                break;
        }

    }

    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        if (stat != null) {
            // 节点存在
            zk.getData(ZkUtil.configPath, this, this, "qwe");
        }
    }

    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        if (data != null) {
            // 拿到了数据
            conf.setConf(new String(data));
            cdl.countDown();
        }
    }
}
